package com.dingding.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingding.gmall.common.dto.SkuRedutionDTO;
import com.dingding.gmall.common.utils.PageUtils;
import com.dingding.gmall.common.utils.Query;
import com.dingding.gmall.common.utils.R;
import com.dingding.gmall.product.dao.SkuInfoDao;
import com.dingding.gmall.product.entity.SkuImagesEntity;
import com.dingding.gmall.product.entity.SkuInfoEntity;
import com.dingding.gmall.product.entity.SkuSaleAttrValueEntity;
import com.dingding.gmall.product.entity.SpuInfoEntity;
import com.dingding.gmall.product.feign.CouponFeignService;
import com.dingding.gmall.product.service.SkuImagesService;
import com.dingding.gmall.product.service.SkuInfoService;
import com.dingding.gmall.product.service.SkuSaleAttrValueService;
import com.dingding.gmall.product.vo.Attr;
import com.dingding.gmall.product.vo.Images;
import com.dingding.gmall.product.vo.Skus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }


    @Override
    public void saveSkuInfos(SpuInfoEntity spuInfoEntity, List<Skus> skus) {
        if (CollectionUtils.isNotEmpty(skus)) {
            for (Skus sku : skus) {
//                String defaultImages = "";
//                for (Images image : item.getImages()){
//                    if (image.getDefaultImg() == 1) {
//                        defaultImages = image.getImgUrl();
//                    }
//                }
                // * 6.1 sku的基本信息 - pms_sku_info
                AtomicReference<String> defaultImg = new AtomicReference<>();
                sku.getImages().forEach(images -> {
                    if (images.getDefaultImg() == 1) {
                        defaultImg.set(images.getImgUrl());
                    }
                });
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatelogId(spuInfoEntity.getCatelogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg.get());
                skuInfoEntity.setPrice(new BigDecimal(sku.getPrice()));
                this.save(skuInfoEntity);

                // * 6.2 sku的图片信息 - pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<Images> images = sku.getImages();
                if (CollectionUtils.isNotEmpty(images)) {
                    List<SkuImagesEntity> collect = images.stream()
                            .map(img -> {
                                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                                skuImagesEntity.setSkuId(skuId);
                                skuImagesEntity.setImgUrl(img.getImgUrl());
                                skuImagesEntity.setDefaultImg(img.getDefaultImg());
                                return skuImagesEntity;
                            })
                            .filter(item -> StringUtils.isNotBlank(item.getImgUrl()))
                            .collect(Collectors.toList());
                    skuImagesService.saveBatch(collect);
                }

                // * 6.3 sku的销售属性信息 - pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                if (CollectionUtils.isNotEmpty(attr)) {
                    List<SkuSaleAttrValueEntity> collect = attr.stream().map(item -> {
                        SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(item, skuSaleAttrValue);
                        skuSaleAttrValue.setSkuId(skuId);
                        return skuSaleAttrValue;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(collect);
                }
                // * 6.4 sku的优惠，满减等信息
                SkuRedutionDTO skuRedutionDTO = new SkuRedutionDTO();
                BeanUtils.copyProperties(sku, skuRedutionDTO);
                skuRedutionDTO.setSkuId(skuId);
                //满几件打几折，满几件优惠
                if (skuRedutionDTO.getFullCount() > 0 || skuRedutionDTO.getFullPrice().compareTo(new BigDecimal(0)) == 1){
                    R r = couponFeignService.saveSkuRedution(skuRedutionDTO);
                    if (r.getCode() != 0) {
                        log.error("远程保存spu积分信息失败");
                    }
                }


            }
        }
    }

    /**
     * t: 1611661726082
     * page: 1
     * limit: 10
     * key:
     * catelogId: 225
     * brandId: 11
     * min: 0
     * max: 0
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)){
            wrapper.and(index -> index.eq("sku_id",key).or().like("sku_name",key));
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId) && !"0".equals(catelogId)){
            wrapper.eq("catelog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId) && !"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String priceMin = (String) params.get("min");
        if (StringUtils.isNotBlank(priceMin)){
            wrapper.ge("price",priceMin);
        }
        String priceMax = (String) params.get("max");
        if (StringUtils.isNotBlank(priceMax)){
            BigDecimal bigDecimal = new BigDecimal(priceMax);
            if (bigDecimal.compareTo(new BigDecimal("0")) > 0) {
                wrapper.le("price",priceMax);
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuInfoBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }
}